package com.adamrocker.android.gorillamd;

import java.util.List;
import twitter4j.Tweet;
import com.adamrocker.android.gorilla.twitter.TwitterSearch;
import com.adamrocker.android.gorilla.util.Kanji2RomaByWeb;
import com.adamrocker.android.gorilla.util.Web;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Dockに挿したら以下の動作をするアプリ 1. Twitterのハッシュタグ検索で文字を拾う 2. 漢字、平仮名をアルファベットに変換する 3.
 * アルファベットをモールス語に変換する 4. モールス語をゴリラ音声に変換して保存する 5. 保存したゴリラ音声を再生する
 * 
 * @author adamrocker
 * 
 */
public class GorillaMDActivity extends Activity {
    private static final String HASHTAG_KEY = "hashtag_key";
    private static final int ANIM = 0;
    private static final int POLL_TWEET = 1;
    private static final int SHOW_TWEET_LOOP = 2;
    private static final int TWEET_LIMIT = 100;
    protected static final long ANIM_DELAY_TIME = 80;
    private static final long TWEET_LOOP_INTERVAL = 10 * 1000;
    private static final int REQUEST_CODE = 777;
    private TextView mHashtagTV;
    private TextView mTweetTV;
    private Button mSetBtn;
    private EditText mSetET;
    private String mHashtag;
    private List<Tweet> mTweets;
    private int mTweetIndex;
    private ImageView mTweetImg;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
            case ANIM:
                AnimText at = (AnimText) msg.obj;
                int index = msg.arg1;
                at.iTv.setText(at.iSb.substring(0, index));
                index++;
                if (index <= at.iSb.length()) {
                    msg = new Message();
                    msg.what = what;
                    msg.arg1 = index;
                    msg.obj = at;
                    sendMessageDelayed(msg, ANIM_DELAY_TIME);
                } else {
                    if (at.iListener != null) {
                        at.iListener.fin();
                    }
                }
                break;
            case POLL_TWEET:
                getTweet();
                break;
            case SHOW_TWEET_LOOP:
                tweetLoop();
                break;
            }
        }
    };
    private TextView mTweetName;
    private Animation mFadein;
    private View mHashEdit;
    private TextView mRomanTV;
    private TextView mConnectTV;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mHashEdit = findViewById(R.id.hash_edit);
        mHashtagTV = (TextView) findViewById(R.id.current_hashtag_tv);
        mHashtagTV.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mHashtagTV.setVisibility(View.GONE);
                mHashEdit.setVisibility(View.VISIBLE);
            }
        });
        mConnectTV = (TextView)findViewById(R.id.connect_tv);
        final String connect = getString(R.string.connect);
        startTextAnimation(connect, mConnectTV, new AnimListener() {
            public void fin() {
                mConnectTV.startAnimation(mFadein);
            }
        });
        
        mSetET = (EditText) findViewById(R.id.hashtag_et);
        mTweetTV = (TextView) findViewById(R.id.tweet_tv);
        mTweetTV.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showTweet();
            }
        });
        mTweetImg = (ImageView) findViewById(R.id.tweet_icon);
        mTweetName = (TextView) findViewById(R.id.tweet_name_tv);
        mSetBtn = (Button) findViewById(R.id.sethashtag_btn);
        mSetBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mHashEdit.setVisibility(View.GONE);
                String hash = mSetET.getText().toString();
                saveSettings(hash);
                hash = loadHashtag(GorillaMDActivity.this);
                mHashtagTV.setVisibility(View.INVISIBLE);
                fadeinTextView(mHashtagTV, hash);
                deleteRoman();
                deleteTweet();
                getTweetWithThread(new Runnable() {
                    public void run() {
                        showTweet();
                    }
                });
                closeKB();
            }
        });
        mRomanTV = (TextView) findViewById(R.id.roman_tv);
        mHashtag = loadHashtag(this);
        mFadein = AnimationUtils.loadAnimation(this, R.anim.fadein);
        fadeinTextView(mHashtagTV, mHashtag);
        
        getTweetWithThread(new Runnable() {
            public void run() {
                mConnectTV.setVisibility(View.GONE);
                showTweet();
            }
        });
    }

    public void onStart() {
        super.onStart();
    }

    public void onStop() {
        super.onStop();
        //killMe();//時間ないので終了処理せずプロセスごと殺す
    }
    
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            //killMe();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    public static final String loadHashtag(Context context) {
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        String hash = sp.getString(HASHTAG_KEY, "#SPhack");
        return hash;
    }

    private final void saveSettings(String hash) {
        Editor edit = PreferenceManager.getDefaultSharedPreferences(this)
                .edit();
        if (!hash.startsWith("#")) {
            hash = "#" + hash;
        }
        edit.putString(HASHTAG_KEY, hash);
        edit.commit();
    }

    private void fadeinTextView(TextView tv, String str) {
        tv.setText(str);
        tv.startAnimation(mFadein);
        tv.setVisibility(View.VISIBLE);
    }

    private void getTweetWithThread(final Runnable run) {
        new Thread(new Runnable() {
            public void run() {
                getTweet();
                mHandler.post(run);
            }
        }).start();
    }

    private void getTweet() {
        String hashtag = loadHashtag(this);
        try {
            mTweets = TwitterSearch.getTweets(hashtag, TWEET_LIMIT);
            mTweetIndex = 0;
        } catch (Exception e) {
            e.printStackTrace();
            String error = getString(R.string.twetter_error);
            startTextAnimation(error, mTweetTV, null);
            Message msg = new Message();
            msg.what = POLL_TWEET;
            mHandler.sendMessageDelayed(msg, 10 * 1000);
        }
    }

    public void startTextAnimation(String text, TextView tv,
            AnimListener listener) {
        StringBuilder sb = new StringBuilder(text);
        Message msg = new Message();
        AnimText at = new AnimText();
        at.iSb = sb;
        at.iTv = tv;
        at.iListener = listener;
        msg.what = ANIM;
        msg.obj = at;
        msg.arg1 = 1;// index
        tv.setVisibility(View.VISIBLE);
        mHandler.sendMessage(msg);
    }

    private void showTweet() {
        if (mTweets == null) {
            return;
        }

        Tweet t = mTweets.get(mTweetIndex++);
        String user = t.getFromUser();
        mTweetName.setText(user);
        mTweetName.startAnimation(mFadein);

        String img_url = t.getProfileImageUrl();
        Bitmap bm = null;
        try {
            bm = Web.getHttpBitmap(img_url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (bm != null) {
            mTweetImg.setImageBitmap(bm);
        } else {
            mTweetImg.setImageResource(R.drawable.twitter_default_icon);
        }
        final String text = t.getText();
        Log.i("GORILLA", user + ", " + text + ", " + img_url);
        startTextAnimation(text, mTweetTV, new AnimListener() {
            public void fin() {
                //showRomanWithThread(text);
                showRoman(text);
            }
        });
    }

    private void deleteTweet() {
        mTweetImg.setImageResource(R.drawable.twitter_default_icon);
        mTweetName.setText("");
        mTweetTV.setText("");
    }

    private void deleteRoman() {
        mRomanTV.setText("");
    }
    
    private void showRoman(final String text) {
        Kanji2RomaByWeb kanji = new Kanji2RomaByWeb();
        final String roma = kanji.getRoman(text);
        mHandler.post(new Runnable() {
            public void run() {
                mRomanTV.setText(roma);
                mRomanTV.invalidate();
                sayUho(roma);
            }
        });
    }

    private void showRomanWithThread(final String text) {
        new Thread(new Runnable() {
            public void run() {
               showRoman(text);
            }
        }).start();
    }

    private void sayUho(String uho) {
        Intent it = new Intent(Intent.ACTION_SEND);
        it.setData(Uri.parse("gorilla://"));
        it.putExtra("gori_message", uho);
        it.putExtra("gori_type", 0);// 0=full, 1=uho, 2=uho+flash
        startActivityForResult(it, REQUEST_CODE);
    }

    private void tweetLoop() {
        showTweet();
        Message msg = new Message();
        msg.what = SHOW_TWEET_LOOP;
        mHandler.sendMessageDelayed(msg, TWEET_LOOP_INTERVAL);
    }

    private void closeKB() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
        View v = mSetET;
        IBinder token = v.getWindowToken();
        imm.hideSoftInputFromWindow(token, 0);
    }

    private void killMe() {
        // Log.i("KILLME", "onReceive");
        final ActivityManager mActMan = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        final List<RunningAppProcessInfo> list = mActMan
                .getRunningAppProcesses();
        final int size = list.size();
        for (int i = 0; i < size; i++) {
            final RunningAppProcessInfo info = list.get(i);
            final int pid = info.pid;
            // Log.i("KILLME", "--" + info.processName + "(" + info.pid + ")");
            final int len = info.pkgList.length;
            for (int j = 0; j < len; j++) {
                // Log.i("KILLME", "----[" + j + "]" + pkg);
                if (info.pkgList[j]
                        .equals("com.adamrocker.android.gorillamd")) {
                    Process.killProcess(pid);
                }
            }
        }
    }
}